package org.monkeyk.util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Shengzhao Li
 */
public abstract class ImageUtils {


    /**
     * Reduce image
     *
     * @param origBytes Original image data
     * @param newWidth  reduce image width
     * @param newHeight reduce image height
     * @return Reduce image data
     * @throws java.io.IOException IOException
     */
    public static byte[] reduce(byte[] origBytes, int newWidth, int newHeight) throws IOException {
        BufferedImage origImg = ImageIO.read(new ByteArrayInputStream(origBytes));
        final int origWidth = origImg.getWidth();
        final int origHeight = origImg.getHeight();
        if (newWidth > origWidth) {
            newWidth = origWidth;
        }
        if (newHeight > origHeight) {
            newHeight = origHeight;
        }

        final Image scaledInstance = origImg.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
        BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);

        final Graphics graphics = newImage.getGraphics();
        graphics.drawImage(scaledInstance, 0, 0, null);
        graphics.dispose();

        final ByteArrayOutputStream output = new ByteArrayOutputStream();
        ImageIO.write(newImage, "JPEG", output);
        return output.toByteArray();
    }

    /**
     * Crop image
     *
     * @param origBytes Original image data
     * @param newWidth  cut image newWidth
     * @param newHeight cut image newHeight
     * @param newX      cut image x (left top)
     * @param newY      cut image y (left top)
     * @return cut image bytes
     * @throws java.io.IOException IOException
     */
    public static byte[] crop(byte[] origBytes, int newWidth, int newHeight, int newX, int newY) throws IOException {
        BufferedImage origImg = ImageIO.read(new ByteArrayInputStream(origBytes));

        final int origWidth = origImg.getWidth();
        final int origHeight = origImg.getHeight();
        if (newX + newWidth > origWidth) {
            newWidth = origWidth;
        }
        if (newY + newHeight > origHeight) {
            newHeight = origHeight;
        }

        Image image = origImg.getScaledInstance(origWidth, origHeight, Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        g.drawImage(image, 0, 0, newWidth, newHeight, newX, newY, newX + newWidth, newY + newHeight, null);
        g.dispose();

        ByteArrayOutputStream bios = new ByteArrayOutputStream();
        ImageIO.write(tag, "JPEG", bios);
        return bios.toByteArray();
    }
}
